package com.xll.utils;

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;

import java.net.MalformedURLException;

public class WatermarkingEventHandler implements IEventHandler {

    public final static String WATER_IMG = "1";

    public final static String WATER_TEXT = "0";

    private PdfFont font;

    private String watermark;

    private String type;

    public WatermarkingEventHandler(PdfFont font, String watermark) {
        this.font = font;
        this.watermark = watermark;
        this.type = WATER_TEXT;
    }

    public WatermarkingEventHandler(PdfFont font, String watermark, String type) {
        this.font = font;
        this.watermark = watermark;
        this.type = type;
    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(),
                page.getResources(),
                pdfDoc);

        if (WATER_TEXT.equals(type)) {

            new Canvas(canvas, pdfDoc, page.getPageSize())
                    .setFontColor(ColorConstants.LIGHT_GRAY)
                    .setFontSize(60)
                    .setFont(font)
                    .showTextAligned(new Paragraph(watermark),
                            298,
                            421,
                            pdfDoc.getPageNumber(page),
                            TextAlignment.CENTER,
                            VerticalAlignment.MIDDLE,
                            45);
        } else {

            try {

                Image image = new Image(ImageDataFactory.create(watermark));
                image.setOpacity(0.3f);
                image.setRotationAngle(340);
                new Canvas(canvas, pdfDoc, page.getPageSize())
                        .setFontColor(ColorConstants.LIGHT_GRAY).add(image);

            } catch (MalformedURLException e) {
            }

        }
    }
}
